# 目标
# 获取  下载  b站  视频


import os
import re
from xml import etree
from lxml import html
etree = html.etree

import requests


class Bli:
    def __init__(self):
        # 1准备起始url 和请求头信息
        self.url =  "https://www.bilibili.com/video/BV1k54y1E7mp? spm_id_from=333.1007.partition_recommend.content.click"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
            'referer': self.url
        }

    def get_data(self):
        # 发送请求获取响应
        response = requests.get(self.url, headers=self.headers)
        return response.content.decode('utf-8')

    def download(self, video_url, audio_url, title):
        print("开始下载")
        # # 视频
        video = requests.get(video_url, headers=self.headers).content
        # # 音频
        audio = requests.get(audio_url, headers=self.headers).content
        # print("开始保存")
        title = title.replace("/", "").replace(" ", "")
        #
        video_name: str = title + "_temp.mp4"
        audio_name = title + "_temp.mp3"
        #
        # # 保存到文件
        with open(video_name, 'wb') as f:
            f.write(video)
        #
        with open(audio_name, 'wb') as f:
            f.write(audio)

        print("保存over")
        self.hecheng(video_name, audio_name, title + ".mp4")

    def hecheng(self, video_name, audio_name, new_name):
        os.system(f'ffmpeg -i {video_name} -i "{audio_name}" -c copy "{new_name}"')

    def parse_data(self, data):
        # 提取数据 video 和 audio 关键字
        html = etree.HTML(data)
        text = html.xpath('//html/head/script[4]/text()')[0]
        # print(text)
        # 获取标题
        title = html.xpath('//h1[@id="video-title"]/span/text()')[0]


        video_url = re.findall(r'"video":.*?,"baseUrl":"(.*?)",', text)[0]

        print("视频地址", video_url)
        audio_url = re.findall(r'"audio":.*?,"baseUrl":"(.*?)",', text)[0]

        print("音频地址", audio_url)

        self.download(video_url, audio_url, title)

    def save_data(self, data_list):
        pass

    def start(self):
        data = self.get_data()
        data_list = self.parse_data(data)
        self.save_data(data_list)


if __name__ == '__main__':
    d = Bli()
    d.start()
